#!/usr/bin/env python
# -*- coding:utf8 -*-

#############################################
# fileName     : ailog.py
# createAt     : 2018-02-06 11:31:58
# modifyAt     : 2018-11-02 17:06:02
# authorIs     : luyi
# authorEmail  : luyiwmm@gmail.com
# description  :
#############################################

from multiprocessing_logging import install_mp_handler
from logging.handlers import TimedRotatingFileHandler
from flask import g
import logging
import socket
import sys

class AiLogger(object):

    logger_name = 'ailogger'

    def __init__(self, service_name="ailog", root_path="logs", level=logging.INFO, multi=False):
        # 加入主机名用于区分多docker实例映射同一目录
        path = '%s/%s-%s.log' % (root_path, service_name, socket.gethostname())
        self.init_logger(self.logger_name, path, level, multi)

    # 初始化python解析器层logger
    def init_logger(self, name, file_path, level, multi):
        logger = logging.getLogger(name)
        formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(process)d - %(reqid)s - %(message)s")
        handler = TimedRotatingFileHandler(file_path, when='midnight', interval=1, backupCount=7)
        handler.setLevel(level)
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(level)
        if multi:
            # 添加多进程handler
            install_mp_handler(logger)

    def utf8(self, s):
        if (sys.version_info <= (3, 0)) and not isinstance(s, unicode):
            s = s.decode('utf8')
        return s

    def reqid(self):
        try:
            reqid = g.get('reqid', '')
        except:
            reqid = ''

        return reqid

    def debug(self, msg):
        msg = self.utf8(msg)
        logger = logging.getLogger(self.logger_name)
        logger.debug(msg, extra={'reqid': self.reqid()})

    def info(self, msg):
        msg = self.utf8(msg)
        logger = logging.getLogger(self.logger_name)
        logger.info(msg, extra={'reqid': self.reqid()})

    def error(self, msg):
        msg = self.utf8(msg)
        logger = logging.getLogger(self.logger_name)
        logger.error(msg, extra={'reqid': self.reqid()})
